package cn.com.elite;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


public class RecordService extends HttpServlet{
	private static final Log log=LogFactory.getLog(RecordService.class);
	private static String URL="";
	private static String companyCode="";
	private static String Filter_URL="";
	private static String Per_URL="";
	private static String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}
	private String UseAxis(String endpoint,String fun_name,String inputXml){
		try{
			Service service=new Service();
			Call call=(Call)service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(endpoint)); 
			call.setOperationName(new QName("http://www.openuri.org/",fun_name));   //要访问的方法
			call.addParameter(new QName("http://www.openuri.org/","companyCode"),XMLType.XSD_STRING,ParameterMode.IN);
			call.addParameter(new QName("http://www.openuri.org/","inputXML"),XMLType.XSD_STRING,ParameterMode.IN);
			call.setReturnType(XMLType.XSD_STRING); //设置返回值类型
            String i=(String)call.invoke(new Object[]{"58582",inputXml});
            return i;
		}catch(Exception e){
			log.error("UseAxis:"+getERRO(e));
			return "";
		}
	}
	private String doReturnXML(String xml){
		try{
			Document document=DocumentHelper.parseText(xml);
	        Element ossresponse=(Element)document.getRootElement();
	        Element Eresult_code=ossresponse.element("result_code");
	        String result_code=Eresult_code.getText();
	        if(result_code.equals("0")){
	        	Element ERECORD_URL=ossresponse.element("params").element("tables").element("table").element("r").element("c");
	        	String RECORD_URL=ERECORD_URL.getText();
	        	if(RECORD_URL!=null&&!RECORD_URL.equals("")&&RECORD_URL.length()>0){
	        		return RECORD_URL;   
	        	}else{
	        		return "false";
	        	}
	        }else{
	        	return "false";
	        }
		}catch(Exception e){
			log.error("doReturnXML:"+getERRO(e));
			return "false";
		}
		
	}
	public static void main(String[] args){
		String endpoint="http://222.77.183.117:82/iservuc/services/DataProxyNew?wsdl";
		String fun_name="callService";
//		String inputXml="<?xml version='1.0' encoding='GBK' ?><input_params><service_name>ODS_GET_RECORD_INFO</service_name><company_id>0</company_id><params><tables><table row_num='1'><r><c>3112062710324883X02D</c><c>58582</c></r></table></tables></params></input_params>";
		String inputXml="<?xml version='1.0' encoding='GBK' ?><input_params><service_name>FF_NBR_DECRYPT</service_name><company_id>0</company_id><params><tables><table row_num='1'><r><c>1356755e712d4ca69ec34df3a74fe60e</c></r></table><table><r><c>58582</c><c>58582</c></r></table></tables></params></input_params>";
		RecordService recordService=new RecordService();
		String xml=recordService.UseAxis(endpoint,fun_name,inputXml);
		System.out.println(xml);
		
//		String xml="<?xml version=\"1.0\" encoding=\"GBK\"?><output_params><result_code>0</result_code><result_msg>调用成功</result_msg><request_serial>T1341379338590R1377</request_serial><service_name>ODS_GET_RECORD_INFO</service_name><params><tables><table row_num=\"1\"><r><c name=\"RECORD_URL\">http://222.77.183.117:82/attachfile/record/oboeu64viw1goku3.wav</c></r></table></tables></params></output_params>";
		
		if(xml!=null&&!xml.equals("")&&xml.length()>0){
			System.out.println(recordService.doReturnXML(xml));
		}
	}
	public void init(){
		URL=this.getInitParameter("URL");
		companyCode=this.getInitParameter("companyCode");
		Filter_URL=this.getInitParameter("Filter_URL");
		Per_URL=this.getInitParameter("Per_URL");
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		String id=request.getParameter("id");
		String fun_name="callService";
		String inputXml="<?xml version='1.0' encoding='GBK' ?>" +
				"<input_params><service_name>ODS_GET_RECORD_INFO</service_name><company_id>0</company_id>" +
				"<params><tables><table row_num='1'><r><c>"+id+"</c><c>"+companyCode+"</c></r></table></tables></params></input_params>";
		log.info("inputXml:"+inputXml);
		String xml=UseAxis(URL,fun_name,inputXml);
		log.info("xml:"+xml);
		if(xml!=null&&!xml.equals("")&&xml.length()>0){
			String RECORD_URL=doReturnXML(xml);
			log.info("RECORD_URL:"+RECORD_URL);
			if(!RECORD_URL.equals("false")){
				try{
					RECORD_URL=RECORD_URL.replace(Per_URL,Filter_URL);
				}catch(Exception e){
					log.error(getERRO(e));
				}
				log.info("Filter_RECORD_URL:"+RECORD_URL);
				response.sendRedirect(RECORD_URL);
			}else{
				try {
					request.setCharacterEncoding("UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					log.error(getERRO(e));
				}
		        response.setContentType("text/html;charset=UTF-8");
		        PrintWriter out;
				try {
					out=response.getWriter();
					out.print(xml);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error(getERRO(e));
				}
			}
		}else{
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				log.error(getERRO(e));
			}
	        response.setContentType("text/html;charset=UTF-8");
	        PrintWriter out;
			try {
				out=response.getWriter();
				out.print(xml);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error(getERRO(e));
			}
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		doGet(request,response);
//		response.setContentType("text/html");
//		PrintWriter out = response.getWriter();
//		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//		out.println("<HTML>");
//		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//		out.println("  <BODY>");
//		out.print("    This is ");
//		out.print(this.getClass());
//		out.println(", using the Post method");
//		out.println("  </BODY>");
//		out.println("</HTML>");
//		out.flush();
//		out.close();
	}


}
